import json
import random
from bot.enterprise_wechat_gpt.util.tair_util import TairUtil
from bot.enterprise_wechat_gpt.config.conf import *

tair_util = TairUtil()


def get_key_url(retry_count=3, model='gpt-4-0613'):
    key_name = get_key_name(model)
    members = tair_util.smembers(key_name)
    if len(members) == 0:
        logging.error(f"{key_name} api-key池为空, 无可用key !!!")
        return None
    key_url = random.choice(list(members))
    key_url = json.loads(key_url)
    key = key_url['key']
    if retry_count == 0:
        logging.info(f"key_url:{key_url} token全部超限, 无可用token, 直接拿一个token")
        return key_url
    if tair_util.exists("QW:ApiKeys:RateLimit:" + key):
        # token超限重新拿一个
        logging.info(f"key_url:{key_url} token超限重新拿一个")
        return get_key_url(retry_count-1)
    return key_url


def get_key_name(model):
    if 'gpt-4' in model:
        key_name = "QW:ApiKeys:GPT4"
    else:
        key_name = "QW:ApiKeys:GPT3"
    return key_name


def remove_key(key, model='gpt-4-0613'):
    key_name = get_key_name(model)
    members = tair_util.smembers(key_name)
    for member in members:
        if json.loads(member)['key'] == key:
            tair_util.srem(key_name, member)
            logging.info(f"key:{key} 移除key成功 原数据:\n{member}")
            break


def set_rate_limit(key):
    tair_util.set_expire("QW:ApiKeys:RateLimit:" + key, 1)


def add_key_url(key_url, model='gpt-4-0613'):
    key_name = get_key_name(model)
    tair_util.sadd(key_name, json.dumps(key_url))


def generate_key_url(url_prefix, keys):
    lines = keys.strip().split('\n')
    for i, line in enumerate(lines):
        key_url = {'url': url_prefix, 'key': line}
        print(json.dumps(key_url))
        add_key_url(key_url)


if __name__ == '__main__':
    keys = """
sk-UU1HhDe16NBCjV95qXFZKAXRJan8PtzvsLOWACqteG7PsYth
sk-LSX6B1ywpkfjNDFb0EcI4zdbyEgjkI78zreuHNsue6xdCs76
sk-JHDmOHViJlNpQijbruWF8uJcOmzF6mPPQBICjwoWf6uAzGum
sk-Xj3JcOoBFb0uYpGbtqwJkv3EAJ0DaRBk6Daq7c1YKY02EIXZ
sk-OyjvYcFxxpANB0Rzgn66cgIgjKbxNo7G1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5kLoxCjPCsx8cQcHhANyTE4zcf
sk-emVWECeH38lRylXmjKrlrY0b7KueI3YWoEi9Jh1nsfXa9VPS
sk-zVfmw61GrpTiTWNeSkdZK7Phd8nP5xijleOKPY7V8Px6p8G8
sk-yLN22ludjQUexPl2e0ZlqtPqXGfhzTEAkvi0Ef68CnxZ2Wm5
"""
    url_prefix = "https://api.xiaojuan.tech"
    # url_prefix = "https://api.chatanywhere.cn"
    generate_key_url(url_prefix, keys)
